import { defineStore } from 'pinia';

import { getUserInfo as userInfoApi, login, logout as logoutApi } from '@/api/auth';
import { getPermission } from '@/api/permission';
import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  id: null,
  nickname: '',
  username: '',
  sex: 0,
  phone: '',
  email: '',
  avatar: '',
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 默认token不走权限
    tokenHead: 'Authorization',
    userInfo: { ...InitUserInfo },
    permissions: Array<string>, // 用户权限列表
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: { username: string; password: string }) {
      const { token, tokenHead } = await login(userInfo);
      this.token = token;
      this.tokenHead = tokenHead;
      // 登录成功后获取用户权限
      const permissions = await getPermission();
      this.permissions = permissions;
    },
    async getUserInfo() {
      const res = await userInfoApi();
      this.userInfo = res;
      // 获取用户权限列表
      const permissions = await getPermission();
      this.permissions = permissions;
    },
    async logout() {
      await logoutApi();
      this.token = '';
      this.userInfo = { ...InitUserInfo };
      this.permissions = Array<string>;
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token', 'tokenHead', 'permissions'],
  },
});
